#include "graphics.h"
#include <math.h>
#include <stdio.h>

/*GRAINCONTROL is a measure of how fine details
* will be displayed. The lesser the value the
* more detail of the print of triangles.
*/
#define GRAINCONTROL 0.05 

/*Private procedures.*/
static void drawTriangle(double penx, double peny, double x1, double y1, double x2, double y2, double x3, double y3);
static void printGroupMembers();

/*Main function.*/
void main(void){

	InitGraphics();

	printGroupMembers();

	drawTriangle(1,1,2, 2, 2, -2, -4, 0);
}

/*
* Procedure: printGroupMembers
* Usage: printGroupMembers();
* --------------------------------
* This procedure prints the authors of this
* program to screen.
*/
static void printGroupMembers(){

	printf("This program was developed by: ");
	printf("Jim Glansk, S141587, ");
	printf("Henrik Wistbacka, S142066\n");
}


/*
* Procedure: drawTriangle
* Usage: drawTriangle(penx, peny,
					  x1, y1, 
					  x2, y2, 
					  x3, y3);
* --------------------------------
* This procedure draws a triangle recursively on screen.
* penx and peny is the start position of the 
* lower left corner of the triangle. x1 and y1
* is the incremental move from the start position.
* x2 and y2 is the incremental move from x1 y1. 
* And last x3 and y3 is the incrental move from 
* x2 y2. GRAINCONTROL is set to a small value
* and the drawing of the triangles stops when 
* the value of X3*X3 is small enough.
*/
static void drawTriangle(double penx, double peny,
						 double x1, double y1,
						 double x2, double y2,
						 double x3, double y3){

	if (x3*x3 < GRAINCONTROL) //x3*x3 will always be positive.
		return;

	MovePen(penx, peny);
	DrawLine(x1, y1);
	DrawLine(x2, y2);
	DrawLine(x3, y3);

	drawTriangle(penx, peny, x1 / 2, y1 / 2, x2 / 2, y2 / 2, x3 / 2, y3 / 2); /*Lower left triangle*/

	drawTriangle(penx + x1 / 2, peny + y1 / 2, x1 / 2, y1 / 2, x2 / 2, y2 / 2, x3 / 2, y3 / 2); /*Higher top triangle*/

	drawTriangle(penx + x1, peny, x1 / 2, y1 / 2, x2 / 2, y2 / 2, x3 / 2, y3 / 2); /*Lower right triangle*/

	drawTriangle(penx + 3.0 / 2.0*x1, peny + y1 / 2, -x1 / 2, -y1 / 2, -x2 / 2, -y2 / 2, -x3 / 2, -y3 / 2); /*Middle center triangle*/

}